package com.pickgliss.render2d
{
	import com.pickgliss.ds.BitmapLib;
	import com.pickgliss.loaders.LoaderManager;
	import com.pickgliss.render2d.events.LayerEvent;
	import com.pickgliss.render2d.vo.LayerInfo;
	import com.pickgliss.render2d.vo.MapItem;
	
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.events.Event;

	public class GraphicLayer extends Shape implements ILayer
	{
		public function GraphicLayer()
		{
		}
		
		private var _info:LayerInfo;
		public function set info(i:LayerInfo):void
		{
			if(_info != null && _info != i)
			{
//				removeInfos
			}
			_info = i;
			_info.addEventListener(LayerEvent.ITEM_ADD,onItemAdd);
			loadAllResource();
		}
		
		public function loadAllResource():void
		{
			for(var i:int = 0;i<_info.mapItems.length;i++)
			{
				loadResource(_info.mapItems[i]);
			}
		}
		
		protected function onItemAdd(event:LayerEvent):void
		{
			loadResource(event.item);
		}
		
		private function loadResource(info:MapItem):void
		{
			LoaderManager.Instance.loadEasy(info.source);
		}
		
		
		public function get info():LayerInfo
		{
			return _info;
		}
		
		public function dispose():void
		{
			_info.removeEventListener(LayerEvent.ITEM_ADD,onItemAdd);
			_info = null;
			if(parent)parent.removeChild(this);
		}
		
		public function render():void
		{
			graphics.clear();
			var count:int = _info.mapItems.length;
			for(var i:int = 0;i<count;i++)
			{
				var item:MapItem = _info.mapItems[i];
				var d:BitmapData = BitmapLib.Instance.getBitmapData(item.source);
				if(d)
				{
					if(item.width < 0)item.width = d.width;
					if(item.height < 0)item.height = d.height;
					graphics.beginBitmapFill(d,item.matrix,true);
					graphics.drawRect(item.x,item.y,item.width,item.height);
					graphics.endFill();
				}
			}
		}
	}
}